﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
using umbraco.BasePages;


namespace DigibizAdvancedMediaPicker
{
    public partial class Installer : System.Web.UI.UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                try
                {
                    SaveSettings(true, true);
                }
                catch (Exception ex)
                {
                    DAMP_Helper.LogException(ex);
                }
            }
        }

        protected void BtnSaveSettings_Click(object sender, EventArgs e)
        {
            try
            {
                SaveSettings(CheckBoxCallCropper.Checked, CheckBoxIfEmpty.Checked);

                //Show a speech bubble the data was succesfully saved.
                BasePage.Current.ClientTools
                    .ShowSpeechBubble(BasePage.speechBubbleIcon.save, "Saved", "The data has been saved succesfully");
            }
            catch (Exception ex)
            {
                DAMP_Helper.LogException(ex);
            }
        }

        private void SaveSettings(bool callImageCropper, bool onlyIfEmpty)
        {
            //Get the web.config.
            Configuration config = WebConfigurationManager.OpenWebConfiguration("~");

            //Get the app settings.
            AppSettingsSection appSettingsSection = config.AppSettings;

            //Save the CallImageCropper value.
            if (appSettingsSection.Settings["DAMP_CallImageCropper"] != null)
            {
                appSettingsSection.Settings["DAMP_CallImageCropper"].Value = callImageCropper.ToString().ToLower();
            }
            else
            {
                appSettingsSection.Settings.Add("DAMP_CallImageCropper", callImageCropper.ToString().ToLower());
            }

            //Save the OnlyIfEmpty value.
            if (appSettingsSection.Settings["DAMP_OnlyIfEmpty"] != null)
            {
                appSettingsSection.Settings["DAMP_OnlyIfEmpty"].Value = onlyIfEmpty.ToString().ToLower();
            }
            else
            {
                appSettingsSection.Settings.Add("DAMP_OnlyIfEmpty", onlyIfEmpty.ToString().ToLower());
            }

            //Save the config file.
            config.Save(ConfigurationSaveMode.Modified);
        }
    }
}